package com.shenzhen.horselive.presenter;


import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class DefaultPresenterFactory implements PresenterFactory {

    public <T extends BasePresenter,V extends BaseView> T create(V target) {
        Class clazz = target.getClass();
        if (clazz.getGenericSuperclass() instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
            Type[] typeArguments = parameterizedType.getActualTypeArguments();
            if (typeArguments.length > 0) {
                Class presenterClazz = (Class) typeArguments[0];
                try {
                    Constructor[] constructors = presenterClazz.getConstructors();
                    for (Constructor constructor : constructors) {
                        if (constructor != null) {
                            if (constructor.getParameterTypes() == null || constructor.getParameterTypes().length == 0) {
                                    return (T) constructor.newInstance();
                            } else if (constructor.getParameterTypes().length == 1) {
                                Class types = constructor.getParameterTypes()[0];
                                if (types.isAssignableFrom(getClass())) {
                                    return (T) constructor.newInstance(target);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        return null;
    }
}
